extends Area2D

signal fire
signal hit_down
signal hit(player: Node)
signal hp_increase(player: Node)

@onready var anim: AnimatedSprite2D = $AnimatedSprite2D
@export var speed = 400

var screen_size
var sprite_size = Vector2(72, 85)
var hp = 100

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	add_to_group("player")
	screen_size = get_viewport_rect().size
	$HpIncreaseTimer.start()
	

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	# var velocity = Vector2.ZERO
	if Input.is_action_pressed("player_move_up"):
		position += Vector2(0, -speed * delta)
	if Input.is_action_pressed("player_move_down"):
		position += Vector2(0, speed * delta)
	if Input.is_action_pressed("player_move_left"):
		position += Vector2(-speed * delta, 0)
	if Input.is_action_pressed("player_move_right"):
		position += Vector2(speed * delta, 0)
	if Input.is_action_just_pressed("player_fire"):
		fire.emit()
	position = position.clamp(Vector2.ZERO, screen_size - sprite_size)

func start(start_position):
	position = start_position
	$CollisionPolygon2D.disabled = false
	

func _on_area_entered(area: Area2D) -> void:
	if area and area.is_visible_in_tree():
		hp -= 10
		hit.emit(self)
		if hp == 0:
			speed = 0
			anim.play("explosion")
			await anim.animation_finished
			queue_free()
			hit_down.emit()
		else:
			flash()

func flash():
	"""
	此函数用来提供敌机被击中时的闪烁效果
	"""
	var tween = create_tween()
	tween.tween_property($AnimatedSprite2D, "modulate", Color.from_rgba8(64, 64, 64), 0.08) # 深色，表示被击中
	tween.tween_property($AnimatedSprite2D, "modulate", Color.from_rgba8(255, 255, 255), 0.0)  # 恢复正常
	


func _on_hp_increase_timer_timeout() -> void:
	#if hp < 100:
		#hp += 1
		#hp_increase.emit(self)
		#if hp > 100:
			#hp = 100
	pass
